package com.hancher.common.androidutil;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.hancher.common.base.BaseApplication;
import com.hancher.money.R;
import com.hancher.plugins.hrlog.HrLogUtil;

import java.lang.reflect.Field;

@SuppressLint("SoonBlockedPrivateApi")
public class ToastUtil {
    private static Toast mToast;
    private static TextView mTvToast;
    private static Field sField_TN;
    private static Field sField_TN_Handler;

    static {
        try {
            sField_TN = Toast.class.getDeclaredField("mTN");
            sField_TN.setAccessible(true);
            sField_TN_Handler = sField_TN.getType().getDeclaredField("mHandler");
            sField_TN_Handler.setAccessible(true);
        } catch (Exception e) {
        }
    }

    /**
     * hook toast 防止 android.view.WindowManager$BadTokenException 异常
     * 仅针对 Android 7
     *
     * @param toast
     */
    private static void hook(Toast toast) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N || Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) {
            try {
                Object tn = sField_TN.get(toast);
                Handler preHandler = (Handler) sField_TN_Handler.get(tn);
                sField_TN_Handler.set(tn, new SafelyHandlerWarpper(preHandler));
            } catch (Exception e) {
                HrLogUtil.e("err=", e);
            }
        }
    }

    public static void show(String content) {
        cancelToast();
        if (mToast == null) {
            mToast = new Toast(BaseApplication.getInstance().getApplicationContext());
//            //设置toast显示的位置，这是居中
//            mToast.setGravity(Gravity.CENTER, 0, 0);
            //设置toast显示的时长
            mToast.setDuration(Toast.LENGTH_SHORT);
            //自定义样式，自定义布局文件
            View _root = LayoutInflater.from(BaseApplication.getInstance().getApplicationContext()).inflate(R.layout.toast_custom_common2, null);
            mTvToast = (TextView) _root.findViewById(R.id.tvCustomToast);
            //设置自定义的view
            mToast.setView(_root);
        }

        if (content == null) {
            content = "系统异常";
        }
        HrLogUtil.d("吐司：" + content);
        if (content.contains("SocketTimeoutException")) {
            mTvToast.setText("服务器连接超时");
        } else if (content.contains("ConnectException") || content.contains("UnknownHostException")) {
            mTvToast.setText("网络异常");
        } else {
            //设置文本
            mTvToast.setText(content);
        }
        hook(mToast);
        //展示toast
        mToast.show();
    }

    public static void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
            mTvToast = null;
        }
    }

}
